const http = require('http');
const querystring = require('querystring');
const fs = require('fs');
const path =require('path')

const server = http.createServer((req,res) => {
    res.writeHead(200,{
		"content-type":"text/html;charset=UTF-8",
        'Access-Control-Allow-Origin': "*"
	}) 
	const method = req.method;
	console.log('请求方法：',method);
	const url = req.url;
	console.log('请求URL',url);
	 
   if (req.url === "/") {
		const tagPage = fs.readFileSync(path.join(__dirname, "./index.html"), {
		  encoding: "utf8",
		});
		res.writeHead(200, { "Content-Type": "text/html" });
		res.write(tagPage);
		res.end();
	} 
	if(req.url === "/css/index.css") {
		const cssTxt = fs.readFileSync(path.join(__dirname, "./css/index.css"), {
			encoding: "utf8",
		  });
		  res.writeHead(200, { "Content-Type": "text/css" });
		  res.write(cssTxt);
		  res.end();
	}
	if(req.url === "/js/axios.js") {
		const ajs = fs.readFileSync(path.join(__dirname, "/js/axios.js"), {
			encoding: "utf8",
		  });
		  res.writeHead(200, { "Content-Type": "text/js" });
		  res.write(ajs);
		  res.end();
	}
	if(req.url === "/js/vue.min.js") {
		const vjs = fs.readFileSync(path.join(__dirname, "/js/vue.min.js"), {
			encoding: "utf8",
		  });
		  res.writeHead(200, { "Content-Type": "text/js" });
		  res.write(vjs);
		  res.end();
	}

	if(req.url === "/images/list_mask.png") {
		const img = fs.readFileSync(path.join(__dirname, "/images/list_mask.png"));
		  res.writeHead(200, { "Content-Type": "image/png" });
		  res.write(img);
		  res.end();
	} 
	if(req.url === "/name.txt") {
		const txt = fs.readFileSync(path.join(__dirname, "./name.txt"),{
			encoding: "utf8",
		  });
		  res.writeHead(200, { "Content-Type": "text/plain" });
		  res.write(txt);
		  res.end();
	}
	req.query = querystring.parse(url.split('?')[1]);   
	if(req.url.includes('/lucky')) {
		fs.writeFileSync("./name.txt" , req.query.name,'utf8')  
		res.end("ok")
	} 
})

server.listen(8080, () => {
	console.log('服务器启动成功！8080端口');
})